/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 10/19/2010
*/

trigger LeadAASFieldUpdateTrigger on Lead (before insert, before update) {
	if(trigger.isBefore){
		List<Lead> leads = new List<Lead>();
		Set<ID> ownerIds = new Set<ID>();
		Set<ID> leadAASRecordTypeID = AASFieldUpdateHelperClass.getLeadAASRecordTypeID();
		if(trigger.isInsert){
			for(Lead l : trigger.new){
				String tPrefix = String.Valueof(l.OwnerId).subString(0,3);
				if(tPrefix == AASFieldUpdateHelperClass.User_Prefix && leadAASRecordTypeID.contains(l.RecordTypeId)){
					leads.add(l);
					ownerIds.add(l.OwnerId);
				}
			}
		}else if(trigger.isUpdate){
			for(Lead l : trigger.new){
				String tPrefix = String.Valueof(l.OwnerId).subString(0,3);
				Lead oldLead = trigger.oldMap.get(l.Id);
				if((l.OwnerId != oldLead.OwnerId || l.Office__c != oldLead.Office__c || l.Sales_Region__c != oldLead.Sales_Region__c ) && tPrefix == AASFieldUpdateHelperClass.User_Prefix && leadAASRecordTypeID.contains(l.RecordTypeId) && !l.isConverted){
					leads.add(l);
					ownerIds.add(l.OwnerId);
				}
			}
		}
		if(!leads.isEmpty()){
			AASFieldUpdateHelperClass.updateAASLeadfields(leads, ownerIds);
		}
	}
}